home *** CD-ROM | disk | FTP | other *** search
- Path: apccorp.apcc.com!root
- From: nfegan@apcc.com (Noel Fegan)
- Newsgroups: comp.lang.c++,comp.os.linux.development.apps,comp.os.linux.misc
- Subject: Re: Are str* functions okay in C++?
- Date: Fri, 15 Mar 1996 16:35:59 GMT
- Organization: American Power Conversion
- Message-ID: <4ic6ba$mhe@apccorp.apcc.com>
- References: <4hpvi0$gt6@news.platinum.com> <Do54G9.4Ly.0.server@indra.com>
- NNTP-Posting-Host: hewie.galway.apcc.com
- X-Newsreader: Forte Free Agent 1.0.82
-
- bear@ (Bear Giles) wrote:
-
-
- > <snip>
- >void procedure (argument...)
- > {
- > static char * buffer = 0;
-
- > if (buffer == 0)
- > buffer = malloc (2048); /* or any _large_ number */
-
- > ...
- > sprintf (buffer, format,...)
- > path = strdup (buffer);
- > ...
- > <snip>
-
- In my experience The use of malloc and free in a C++ application should be
- avoided. From what I've read this is generally what is advised. This would also
- mean that functions like strdup should be avoided also, because, as you
- mentioned, you have to use free on the memory block returned by strdup, not
- delete. I'm sure you are very careful with this but others maintaining you code
- may not realise the implications.
-
- I'm not saying that they do not work but it introduce the potential problem
- where free is using on a "new"ed memory block, etc.
-
- Apart from this, I do not follow your reason for using a "captive memory leak".
- This memory block is not deleted at any stage during the program, and as such is
- a memory leak as you mentioned. You rely on the good nature of the operating
- system to clean up all the memory taken by the program when it has finished
- executing, even if the program does not delete it itself. I'm think this is a
- bit risky. If you main concern is fragementation of memory or stack size why not
- have the following:
-
- void procedure (argument...)
- {
- static char buffer[2048];
-
- ...
- sprintf(buffer, format,...);
- path = new char[strlen(buffer)+1];
- strcpy(path, buffer);
- ...
-
- This would be a static buffer which is allocated by the program when it is
- initializing and free when the program terminates, there is no memory leak and
- the memory does not get fragmented.
-
- I would recommend using a string class instead of having to add lines like "path
- = new ..." and the "strcpy(..." every time you want to copy a string. Or you
- could write a function which did the equivalent of strdup but used new instead
- of malloc.
- --
- Noel Fegan
- European Software Development Department
- American Power Conversion
- I don't speak for APC...
- nfegan@apcc.com
-
-